<template>
  <view>
    <nav-bar>{{ comment_status !== 2 ? "未批改" : "已提交且点评" }} </nav-bar>

    <view class="order-push">
      <view class="order-header">
        <view class="order-right">
          <image class="order-avater" :src="avatar"></image>
        </view>

        <view class="order-left">
          <view class="order-title">
            <span class="c_name">{{ c_name }}</span>
            <span class="submit_time">{{ submit_time }}</span>
          </view>
          <view class="order-sub">
            {{ l_name }}
          </view>
        </view>
      </view>

      <canvas
        canvas-id="canvas"
        class="canvas"
        style="width: 670rpx; height: 850rpx;"
      ></canvas>
      <cover-image
        :src="correct_display"
        v-if="show_correct_display"
        class="small-pic"
      ></cover-image>

      <view class="audio" v-show="comment_status === 2">
        <image
          v-show="!pause"
          @tap="Pause"
          class="audio-img"
          src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/paly-pause/btn_stop_h@2x.png"
        ></image>
        <image
          v-show="pause"
          class="audio-img"
          @tap="play"
          src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/paly-pause/btn_play_h@2x.png"
        ></image>
        <view class="audio-progress">
          <view
            :style="{ marginLeft: marginLeft + '%' }"
            class="btn"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
          ></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { ajax } from "../../utils/ajax";
  import { mapState } from "vuex";

  export default {
  name: "commit",
  data() {
    return {
      startX: 0,
      marginLeft: 0,
      _marginLeft: 0,
      progressWidth: "",
      btnWidth: 0,
      Max: 0,
      time: 0,
      audio: {},
      pause: true,
      btnList: [
        {
          y: "btn_tick_s@2x",
          g: "btn_tick_n@2x",
          e: "ico_tick_h@2x.png",
          isSlected: false,
          name: "right"
        },
        {
          y: "btn_wrong_s@2x",
          g: "btn_wrong_n@2x",
          e: "ico_del_h@2x.png",
          isSlected: false,
          name: "error"
        },
        {
          y: "btn_circle_s@2x",
          g: "btn_circle_n@2x",
          isSlected: false,
          e: "pic_circle_h@2x.png",
          name: "round"
        },
        {
          y: "btn_line_s@2x",
          g: "btn_line_n@2x",
          e: "pic_line_h@2x.png",
          isSlected: false,
          name: "line"
        },
        {
          y: "btn_example_s@2x",
          g: "btn_example_n@2x",
          e: "ico_tick_h@2x.png",
          isSlected: false,
          name: "expm"
        }
      ],
      bg: "pic_read@2x.png",
      ctx: {},
      editSize: 60,
      canvasWidth: 335,
      canvasHeight: 425,
      originCanvasWidth: 335,
      correct_display: "",
      show_correct_display: false,
      c_name: "",
      l_name: "",
      nick_name: "",
      picture: "",
      comment_audio: "",
      comment_content: "",
      comment_status: 0,
      done: [],
      avatar: "",
      submit_time: ""
    };
  },
  computed: mapState("User", ["token"]),
  methods: {
    async getShow(id) {
      const { token } = this;
      const res = await ajax({
        url: "/api/user/work/show",
        method: "GET",
        data: { token, id }
      });
      if (res.code === 1) {
        this.comment_status = res.data.comment_status;
        this.correct_display = res.data.correct_display;
        this.bg = res.data.picture;
        this.c_name = res.data.c_name;
        this.l_name = res.data.l_name;
        this.nick_name = res.data.nick_name;
        this.picture = res.data.picture;
        this.comment_audio = res.data.comment_audio;
        this.comment_content = res.data.comment_content;
        this.avatar = res.data.avatar;
        this.submit_time = res.data.submit_time;
        this.done =
          res.data.comment_content == null
            ? []
            : JSON.parse(res.data.comment_content);
      }
    },

    touchStart(e) {
      const { pageX, audio } = e.touches[0];
      const { marginLeft } = this;

      this.Pause();

      this.startX = pageX;
      this._marginLeft = marginLeft;
    },

    touchMove(e) {
      const { pageX } = e.touches[0];
      const { _marginLeft, startX, progressWidth, btnWidth, Max } = this;
      const _width = progressWidth - btnWidth;

      const Min = 0;
      const change = pageX - startX;
      let marginLeft = _marginLeft + (change / _width) * 100;

      marginLeft = marginLeft > Max ? Max : marginLeft;
      marginLeft = marginLeft < Min ? Min : marginLeft;
      this.marginLeft = marginLeft;
      this.Max = Max;
    },

    touchEnd() {
      const { audio, marginLeft, Max } = this;
      const { duration } = audio;

      const currentTime = Math.floor((duration / Max) * marginLeft);
      console.log(currentTime);
      audio.seek(currentTime);
      this.play();
    },

    play() {
      const src =
        "https://fangtiyuwen.oss-cn-beijing.aliyuncs.com/admin_files/2ff0721f89347ce62da9a2a3b4493ddc.mp3";

      const { audio, comment_audio } = this;
      audio.src = comment_audio;

      audio.play();
      this.pause = false;
    },

    Pause() {
      const { audio } = this;
      audio.pause();
      this.pause = true;
    },

    /////////////// canvas
    async downImgs(urls) {
      return urls.map(async (item, key) => {
        return await this.downloadFile(
          item.includes("https")
            ? item
            : "https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/" +
                item
        );
      });
    },

    async downloadFile(url) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url,
          success: function(res) {
            switch (res.statusCode) {
              case 200:
                resolve(res.tempFilePath);
                break;
              case 404:
                wx.hideLoading({
                  complete: (res) => {
                    wx.showToast({
                      title: '图片加载失败',
                      icon:'none'
                    })
                  },
                });
                reject(res)
            }
          }
        });
      });
    },

    async drawBack() {
      const { ctx, ePath, backImgInfo, canvasWidth, canvasHeight } = this;
      const { width, height, _height, _width } = backImgInfo;
      await ctx.drawImage(
        await ePath[5],
        0,
        0,
        width,
        height,
        0,
        0,
        canvasWidth,
        canvasHeight
      );
    },

    backImgInfo() {
      return new Promise(async resolve => {
        const { canvasWidth, canvasHeight, ePath } = this;
        uni.getImageInfo({
          src: await ePath[5],
          success: async e => {
            const { width, height } = e;

            let _width, _height;
            if (width < height) {
              _height = canvasHeight;
              _width = Math.floor((width * _height) / height);
            } else {
              _width = canvasWidth;
              _height = Math.floor((_width * height) / width);
            }
            this.backImgInfo = {
              width,
              height,
              _height,
              _width
            };

            resolve({
              width,
              height,
              _height,
              _width
            });
          }
        });
      });
    },
    async drawEditor(x, y, btnIndex) {
      const { ePath, ctx, editSize, canvasWidth, originCanvasWidth } = this;
      const img = await ePath[btnIndex];

      const r = canvasWidth / originCanvasWidth;

      const _editSize = (editSize * r) / 2;

      x = x * r - _editSize / 2;
      y = y * r - _editSize / 2;

      ctx.drawImage(img, 0, 0, editSize, editSize, x, y, _editSize, _editSize);
    },

    drawHistory(curTime) {
      const { done } = this;
      done.forEach(({ x, y, btnIndex, time }) => {
        if (time >= curTime) return;
        this.drawEditor(x, y, btnIndex);
        if (btnIndex === 4) {
          this.show_correct_display = true;
        }
      });
    },

    drawSteps(x, y, btnIndex) {
      this.drawBack();
      this.drawEditor(x, y, btnIndex);
      this.drawHistory();
    }
  },
  onUnload() {
    this.audio.destroy();
    this.marginLeft = 0;
    this._marginLeft = 0;
  },
  mounted() {
    // #ifdef APP-PLUS

    const Max = uni.getStorageSync('Max');
    console.log(1,1,1,1,Max);
    if (Max) {
     return  this.Max  = Max;
    }

    const query = uni.createSelectorQuery();
    query.select(".audio-progress").boundingClientRect();
    query.select(".btn").boundingClientRect();
    query
      .select(".canvas")
      .boundingClientRect()
      .exec(res => {
        const [
          { width: progressWidth },
          { width: btnWidth },
          { width: canvasWidth, height: canvasHeight }
        ] = res;
        const _width = progressWidth - btnWidth;
        const Max = (_width / progressWidth) * 100;

        this.btnWidth = btnWidth;
        this.progressWidth = progressWidth;
        this.Max = Max;
        uni.setStorageSync('Max',Max);
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
      });
    // #endif

  },
  onLoad: async function(options) {
    await this.getShow(options.id);

    // #ifdef MP-WEIXIN

    const query = uni.createSelectorQuery();
    query.select(".audio-progress").boundingClientRect();
    query.select(".btn").boundingClientRect();
    query
      .select(".canvas")
      .boundingClientRect()
      .exec(res => {
        const [
          { width: progressWidth },
          { width: btnWidth },
          { width: canvasWidth, height: canvasHeight }
        ] = res;
        const _width = progressWidth - btnWidth;
        const Max = (_width / progressWidth) * 100;

        this.btnWidth = btnWidth;
        this.progressWidth = progressWidth;
        this.Max = Max;
        if (Max){
          uni.setStorageSync('Max',Max);
        }
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
      });

    // #endif

    const ctx = uni.createCanvasContext("canvas", this);

    const audio = uni.createInnerAudioContext();
    audio.onCanplay(e => {
      console.log(e, audio.duration);
    });
    audio.onPlay(e => {
      console.log("开始播放");
    });
    audio.onTimeUpdate(e => {
      console.log("onTimeUpdate", audio);
      const { currentTime, duration } = audio;
      const { Max } = this;
      console.log(marginLeft, Max, currentTime, duration);
      const marginLeft = (currentTime / duration) * Max;
      const time = Math.floor(currentTime);
      this.drawBack();
      this.drawHistory(time);
      ctx.draw();
      this.marginLeft = marginLeft;
      this.time = time;
    });

    audio.onEnded(e => {
      const { Max } = this;
      this.marginLeft = Max;
      this.pause = true;
    });

    this.audio = audio;

    /////////////////////////////// canvas
    const { bg, btnList } = this;

    const eList = [...btnList.map(item => item.e), bg];
    uni.showLoading({
      title: "数据加载中"
    });

    this.ePath = await this.downImgs(eList);
    this.ctx = ctx;
    await this.backImgInfo();
    await this.drawBack();
    ctx.draw();
    uni.hideLoading();
  }
};
</script>

<style>
.order-push {
  padding: 40rpx;
  text-align: center;
}

.order-header {
  display: flex;
  align-items: center;
}

.order-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.order-title {
  display: flex;
  font-size: 40rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: rgba(39, 60, 61, 1);
}

.order-sub {
  font-size: 32rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(93, 100, 115, 1);
  margin-top: 16rpx;
}

.order-right {
  display: flex;
  align-items: center;
}

.order-avater {
  width: 144rpx;
  height: 144rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.name {
  font-size: 32rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: rgba(93, 100, 115, 1);
}

canvas {
  margin: 62rpx auto 10rpx;
}

.audio {
  display: flex;
  align-items: center;
  width: 670rpx;
  height: 80rpx;
  background: linear-gradient(
    180deg,
    rgba(255, 211, 34, 1) 0%,
    rgba(255, 186, 0, 1) 100%
  );
  border-radius: 40rpx;
  padding: 12rpx;
  box-sizing: border-box;
  margin-top: 10rpx;
}

.audio-img {
  width: 60rpx;
  height: 60rpx;
}

.audio-progress {
  position: relative;
  display: flex;
  align-items: center;
  width: 544rpx;
  height: 4rpx;
  background: rgba(255, 255, 255, 1);
  border-radius: 5px;
  margin-left: 20rpx;
}

.btn {
  transform: all 0.3s ease;
  width: 24rpx;
  height: 24rpx;
  background: rgba(255, 255, 255, 1);
  border-radius: 50%;
}

.small-pic {
  position: relative;
  z-index: 999999;
  display: block;
  margin-top: -150rpx;
  margin-left: 68vw;
  right: 50rpx;
  width: 164rpx;
  height: 164rpx;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 4rpx 36rpx 0px rgba(122, 137, 130, 0.14);
  border-radius: 12rpx;
}

.submit_time {
  font-size: 28rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(144, 150, 163, 1);
}
</style>
